

import SwiftUI

struct VpnView: View {
    @Environment(\.presentationMode) var presentationMode
    @Binding var showDetail: Bool
    @State var isSpeed = false
    @State var isMap = false
    @State private var isConnect = false
    @State private var isConnecting = false
    @State private var isNode = false
    @State var coStatus = false

    @State private var ipAddress: String = ""

    @State private var vpnConfigs: [VpnConfig] = []
    @StateObject private var viewModel = TimerViewModel()

    @StateObject private var vpnStatusManager = VPNStatusManager()

    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
             
                ZStack(alignment: .top, content: {
                    Image("vv")
                        .resizable()
                        .frame(minWidth:0,maxWidth: .infinity ,minHeight:0,maxHeight: 344)
                    
                    VStack {
                        HStack {
                            Image("back")
                                .padding(.leading)
                                .onTapGesture {
                                    withAnimation {
                                        showDetail = false
                                        self.presentationMode.wrappedValue.dismiss()
                                    }
                                }
                            Spacer()
                            Text("Vpn")
                                .font(.title)
                                .fontWeight(.bold)
                                .foregroundColor(.white)
                                .padding(.trailing, 36)
                            Spacer()
                        }
                        .padding(.top,UIApplication.statusBarHeight)
                        
                        Text(buttonTitle)
                            .foregroundStyle(Color.white)
                            .padding(.top,10)
                        
                        Text("\(viewModel.timeString)")
                            .font(.title)
                            .fontWeight(.bold)
                            .foregroundStyle(Color.white)
                            .padding(.top,5)
                            
                        
//                        Button(action: {
//                            handleVPNConnection { result in
//                                switch result {
//                                case .success(let connected):
//                                    coStatus = connected
//                                    if connected {
//                                        viewModel.startTimer()
//                                    } else {
//                                        viewModel.stopTimer()
//                                    }
//                                case .failure:
//                                    coStatus = false
//                                    viewModel.stopTimer()
//                                }
//                            }
//                               
//                        }, label: {
//                            Image(coStatus ? "co" : "de").padding(.top,30)
//                        })
//                   
                           
                        Button {
                            isNode = true
                        } label: {
                            
                            HStack{
                                Image("flag")
                               
                                VStack(alignment: .leading, content: {
                                    
                                        Text("America")
                                        .foregroundStyle(Color.black)
                                    Text("Ip: \(ipAddress)")
                                        .foregroundStyle(Color.black)
                                    
                                }).padding(.leading,10)
                                Spacer()
                                Image("vne")
                            }
                                .padding()
                                .background(Color.white) // 灰色背景
                                .cornerRadius(20) // 20dp 圆角
                                .overlay(
                                    RoundedRectangle(cornerRadius: 20)
                                        .stroke(Color("coco"), lineWidth: 2) // 红色边框
                                )
                                .padding(.horizontal)
                                .padding(.top,10)
                            
                        }

                    
                        
                        VStack{
                            Button(action: {
                                isSpeed = true
                            }, label: {
                                HStack{
                                    Image("sped")
                                    
                                Spacer()
                                    
                                    Text("SpeedTest")
                                        .foregroundColor(.black)
                                    Spacer()
                                    
                                    Image("nex")
                                }.padding(.horizontal)
                            })
                            
                            Image("line")
                                .resizable()
                                .frame(height: 2)
                                .padding(.horizontal, 20)
                            
                            HStack{
                                Image("map")
                                
                            Spacer()
                                
                                Text("Map")
                                Spacer()
                                
                                Button {
                                    isMap = true
                                } label: {
                                    Image("nex")
                                }

                            }.padding(.horizontal)
                                .padding(.top,10)
                            
                            Image("line")
                                .resizable()
                                .frame(height: 2)
                                .padding(.horizontal, 20)
                        }
                        .padding(.top,10)
                        
                    }.onAppear{
                        if let ip = getIPAddress() {
                            ipAddress = ip
                        }
                    }
                    
                   
                })
                   
               
                
                NavigationLink(destination: Speed()  , isActive: $isSpeed) {
                    EmptyView()
                } .hidden()
                    .navigationBarHidden(true)
                
                
                NavigationLink(destination: NodeView()  , isActive: $isNode) {
                    EmptyView()
                } .hidden()
                    .navigationBarHidden(true)
                
                
                NavigationLink(destination: MapView()  , isActive: $isMap) {
                    EmptyView()
                } .hidden()
                    .navigationBarHidden(true)
                
                Spacer()
            }
            .onAppear{
                NetworkManager().fetchVpnConfig { configs in
                    vpnConfigs = configs
                    print("Fetched \(configs.count) VPN configurations")
                    downloadAllVPNConfigs(vpnConfigs:vpnConfigs)
                } failure: { error in
                    print("下载失败", error.localizedDescription)
                }
            }
            .edgesIgnoringSafeArea(.top)
            .navigationViewStyle(StackNavigationViewStyle())
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
        } .navigationViewStyle(StackNavigationViewStyle())
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
    }
    
    
    private var buttonTitle: String {
        switch vpnStatusManager.vpnStatus {
        case .connected:
            return "Disconnect"
        case .connecting:
            return "Connecting"
        case .disconnected, .invalid, .disconnecting:
            return "Connect"
        default:
            return "Unknown"
        }
    }

//    private func toggleVPNConnection() -> () -> Void {
//        return {
//            switch vpnStatusManager.vpnStatus {
//            case .connected:
//                VpnManager.shared.disconnect()
//            case .disconnected, .invalid, .disconnecting:
//                VpnManager.shared.connect()
//            default:
//                break
//            }
//        }
//    }

//    private func handleVPNConnection(completion: @escaping (Result<Bool, Error>) -> Void) {
//        let toggleAction = toggleVPNConnection()
//        toggleAction()
//        
//        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
//            switch vpnStatusManager.vpnStatus {
//            case .connected:
//                completion(.success(true))
//            case .disconnected, .invalid, .disconnecting:
//                completion(.success(false))
//            default:
//                completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
//            }
//        }
//    }


    private func handleVPNConnections(completion: @escaping (Result<Bool, Error>) -> Void) {
        
        print("获得焦点执行")
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
            switch vpnStatusManager.vpnStatus {
            case .connected:
                completion(.success(true))
            case .disconnected, .invalid, .disconnecting:
                completion(.success(false))
            default:
                completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
            }
        }
    }
}

struct VpnView_Previews: PreviewProvider {
    static var previews: some View {
        VpnView(showDetail: .constant(false))
    }
}

